<template>
   <div class="detailPage2-container">
       <div class="d-c-table">
           <el-table
               :data="tableData"
               class="table-box"
               @selection-change="handleSelectionChange"
               :height="tableHeight"
           >
               <el-table-column
                   type="selection"
                   fixed
                   width="55"
               >
               </el-table-column>
               <template v-for="(item, index) in titleList">

                   <el-table-column
                       :prop="item.prop"
                       :label="item.newTitle"
                       min-width="180"
                       :key="`table-column${index}`"
                       v-if="item.newValueKindId === '5' && data.title.length -1>=index"
                   >
                       <template  slot-scope="row">
                           <el-image
                               style="width: 100px; height: 100px"
                               :src="handleImg(row, item)[0]"
                               :preview-src-list="handleImg(row, item)">
                           </el-image>
                       </template>
                   </el-table-column>

                   <el-table-column
                       :prop="item.prop"
                       :label="item.newTitle"
                       min-width="180"
                       :key="`table-column${index}`"
                       v-else-if="item.newValueKindId === '5'"
                   >
                       <template  slot-scope="row">
                           <upLoad-cos
                               @onUpdate="onUpdateImg(arguments[0], row.row.id, index)"
                               :limit="9"
                               :customList="true"
                               :accept="`.bmp,.jpg,.jpeg,.png,.gif`"
                               type="form-data"
                               fileType="img"
                               :key="row.row.id"
                               :list="listData[row.row.id][`titleList${index}`]|| []"
                               class="image-upload-box"
                           >
                           </upLoad-cos>
                       </template>
                   </el-table-column>
                   <el-table-column
                       :prop="item.prop"
                       :label="item.newTitle"
                       min-width="200"
                       :key="`table-column${index}`"
                       v-else-if="item.newValueKindId === '8'"
                   >
                       <template slot-scope="row">
                           <div class="video-box" v-if="row.row[`titleList${index}`]">
                               {{row.row[`titleList${index}`].formName}}
                               <img class="delete" src="~@/assets/file-delete.png" alt="" @click.stop="deleteFile(row.row.id, index)">
                           </div>
                           <up-load-drag
                               v-else
                               @onSuccess="onUpdate(arguments[0], row.row.id, index)"
                               :limit="1"
                               :customList="true"
                               :accept="`.mp4,.m2v,.mkv,.rmvb,.wmv,.avi,.flv,.mov,.m4v`"
                               type="form-data"
                               fileType="video"
                               style="width: 50px"
                           >
                               <el-button size="mini" type="text">上传视频</el-button>
                           </up-load-drag>
                       </template>

                   </el-table-column>
                   <el-table-column
                       :prop="item.prop"
                       :label="item.newTitle"
                       min-width="150"
                       :key="`table-column${index}`"
                       v-else
                   >
                   </el-table-column>
               </template>
           </el-table>


       </div>
       <div class="page-box">
           <div class="page-message">
               <span>已选 <span class="fsz-18">{{ delCount }}</span> | 条</span>
               <el-button type="primary" @click="del" class="btn">删除</el-button>
           </div>
           <div class="pagination-container">
               <el-pagination  :total="total" :page.sync="pageIndex"  :page-size="pageSize" @size-change="handlePage('size',arguments[0] )" @current-change="handlePage('page',arguments[0])" layout='total, sizes, prev, pager, next, jumper'/>
           </div>
           </div>
   </div>
</template>

<script lang="ts">
import { Component, Vue, Prop, Watch } from "vue-property-decorator";
import { isNone, deepCopy } from "@/utils";
import UpLoadDrag from "@core/upload-drag/index.vue";
import UpLoadCos from "@core/upload-cos/index.vue";

type titleListType = {
    newValueKindId: string;
    newTitle: string;
    prop: string;
    id?: number;
    isDel?: boolean;
}
type BaseType = {
    cityCode: any;
    excelPath: string;
    formDescription: string;
    formName: string;
    [key: string]: any;
}
@Component({
    name: "detailPageNotAlive",
    components: {
        UpLoadDrag,
        UpLoadCos
    }
})
export default class DetailPage2 extends Vue {
    @Prop({
        type: Object,
        default() {
            return null;
        }
    })data: any

    @Prop({
        type: Object,
        default() {
            return null;
        }
    })excelAddData: any


    @Watch('data', { immediate: true })
    getData(newVal: any) {
        if (this.listData.length === 0) {
            const list: titleListType[] = this.excelAddData.list;
            this.titleList = list.map((item: titleListType, index: number) => {
                return {
                    newValueKindId: item.newValueKindId,
                    newTitle: item.newTitle,
                    isDel: false,
                    prop: 'titleList' + index
                };
            });
            this.listData = newVal.data.map((item: any, index: number) => {
                const res: any = {};
                for (let i = 0; i < list.length; i++) {
                    if (isNone(item[i])) {
                        res['titleList' + i] = null;
                    } else {
                        res['titleList' + i] = item[i];
                    }
                }
                res.id = index;
                return res;
            });
        }
        const listData = deepCopy(this.listData).filter((item: any) => !item.isDel);
        this.tableData = listData.splice((this.pageIndex - 1) * this.pageSize, this.pageSize);
        this.total = this.listData.filter((item: any) => !item.isDel).length;
    };


    listData: any[] =[] // 总的数据
    tableData: any[]= [] // 显示的table数据
    titleList: titleListType[] =[] // th的list
    delSelect: titleListType[] =[] // 要删除的序号

    delCount= 0
    total= 0
    pageIndex = 1
    pageSize = 10
    tableHeight = 0

    handleSelectionChange(data: any) {
        this.delCount = data.length;
        this.delSelect = data;
    }


    del() {
        const data = deepCopy(this.listData);
        const delSelect = this.delSelect.map((item: titleListType) => item.id);
        for (let i = 0; i < data.length; i++) {
            if (delSelect.includes(i)) {
                data[i].isDel = true;
            }
        }
        this.listData = data;
        this.getData(data);
    }

    created() {
        this.$nextTick(() => {
            this.getTableHeight();
            window.addEventListener("resize", this.getTableHeight);
            this.$on('hook:beforeDestroy', () => {
                window.removeEventListener("resize", this.getTableHeight);
            });
        });
    }


    handlePage(type: string, data: number) {
        if (type === 'size') {
            this.pageSize = data;
            this.pageIndex = 1;
        } else {
            this.pageIndex = data;
        }
        this.getData(this.listData);
    }

    // 导入数据
    async handleImport() {
        const base: BaseType = this.excelAddData.base;
        const list: titleListType[] = this.excelAddData.list;
        const title: string[] = this.data.title; // 原本的title
        const titleForm: string[] = []; // 原本的title
        const valueKindIdList: string[] = []; //  原本的类型
        const newTitle: string[] = []; //  新增的title
        const newValueKindIdList: string[] = []; // 新增的类型
        const newData: any[] = []; // 新增的数据
        const deleteRows = this.listData.filter((item: any) => item.isDel).map((item: any) => item.id); // 删除的数据


        title.forEach((item: string, index: number) => {
            valueKindIdList.push(list[index].newValueKindId);
            titleForm.push(list[index].newTitle);
        });


        for (let i = title.length; i < list.length; i++) {
            newTitle.push(list[i].newTitle);
            newValueKindIdList.push(list[i].newValueKindId);
        }


        this.listData.forEach((item: any, index: number) => {
            newData[index] = [];
            for (let i = title.length; i < list.length; i++) {
                const current = item[`titleList${i}`];
                let data: any = null;
                if (list[i].newValueKindId === '8') {
                    data = isNone(current)
                        ? null
                        : current.path;
                } else if (list[i].newValueKindId === '5') {
                    data = isNone(current)
                        ? null
                        : current.join(',');
                } else {
                    data = current;
                }
                newData[index].push(data);
            }
        });


        const data = {
            townCityCode: base.cityCodeLast,
            excelPath: base.excelPath,
            formDescription: base.formDescription,
            formName: base.formName,
            title: titleForm,
            valueKindIdList,
            deleteRows,
            newData,
            newTitle,
            newValueKindIdList
        };


        const loading = this.$loading({
            body: true,
            text: '导入中'
        });


        const rs = await this.$server["importCreate/thirdImport"]({
            data
        });
        if (rs.data.code === 200) {
            const self = this;
            this.$message({
                type: 'success',
                message: '导入成功',
                duration: 2000,
                onClose() {
                    loading.close();
                    self.$router.push({ name: 'ImportCreateList' });
                }
            });
        } else {
            loading.close();
            this.$message.error(rs.data.message || "接口请求错误!");
        }
    }


    // 上传视频
    onUpdate(data: any, id: number, index: number) {
        this.listData.map((item: any) => {
            if (item.id === id) {
                item[`titleList${index}`] = {
                    path: data.path,
                    formName: data.formName
                };
            }
            return item;
        });
        this.getData(this.data);
    }

    // 删除视频
    deleteFile(id: number, index: number) {
        this.listData.map((item: any) => {
            if (item.id === id) {
                item[`titleList${index}`] = null;
            }
            return item;
        });
        this.getData(this.data);
    }


    // 上传图片
    onUpdateImg(data: any, id: number, index: number) {
        this.listData.map((item: any) => {
            if (item.id === id) {
                item[`titleList${index}`] = data.map((i: any) => i.url);
            }
            return item;
        });
    }


    getTableHeight() {
        this.$nextTick(() => {
            try {
                const table = document.querySelector('.d-c-table');
                if (table) {
                    const tableTop = table.getBoundingClientRect().top; // table距离顶部的高度
                    this.tableHeight = window.innerHeight - tableTop - 94;
                }
            } catch (e) {
                console.log(e);
            }
        });
    }


    handleImg(row: any, item: any) {
        try {
            let data = row.row[item.prop];
            data = JSON.parse(data);
            data = data.map((val: any) => this.$staticUrl + val);
            return data;
        } catch (e) {
            return [];
        }
    }
}
</script>

<style scoped lang="scss">
.detailPage2-container{
    display: flex;
    flex-direction: column;
    height: 100%;
    ::v-deep{
        table{
            width: 100%;
        }
        .el-table-column--selection .cell{
            padding-left: 14px;
        }
        .el-table th{
            background: #F7F7F7;
            line-height: 22px;

            font-size: 14px;
            font-weight: bold;
            color: #37383a;
        }

        .td-is-del{
            display: none;
        }
        .video-box{
            display: flex;
            align-items: center;
            img{
                width: 18px;
                margin-left: 5px;
                cursor: pointer;
                display: none;
            }
            &:hover{
                img{
                    display: block;
                }
            }
        }
        .image-slot{
            i{
                font-size: 30px;
                cursor: pointer;
            }
        }

        .custom-file-list{
            max-height: none;
            overflow: visible;
        }
        .custom-file-list li{
            width: 100%;
        }
        .image-upload-box{
            .el-upload{
                text-align: left;
            }
        }
    }

    .d-c-table{
        display: flex;
        flex: 1;
    }
    .page-box{
        display: flex;
        width: 100%;
        justify-content: space-between;
        align-items: flex-end;
        .page-message{
            padding: 14px 16px;
            font-size: 13px;
        }
        .fsz-18{
            font-size: 18px;
        }
        .btn{
            margin-left: 10px;
        }
    }

    .table-box{
        overflow: auto;

    }


    .pagination-container {
        text-align: right;
        padding: 14px 16px;
    }

    .pagination-container.hidden {
        display: none;
    }

    .el-pagination {
        display: flex;
        align-items: center;
        justify-content: flex-end;
    }


    .none{
        display: none;
    }

}

</style>
